import lmd5 from './md5'

function params(json) {
	if (!json) return ''
	return cleanArray(
		Object.keys(json).map(key => {
			if (json[key] === undefined) return ''
			return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
		})
	).join('&')
}

function generateMixed(n) {
	var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
		'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
		'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
		'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
		'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
	];
	var res = "";
	for (var i = 0; i < n; i++) {
		var id = Math.floor(Math.random() * 36);
		res += chars[id];
	}
	return res;
}
const request = (options) => {
	var timestamp = new Date().getTime();
	var appId = 1001;
	var nonce = generateMixed(6);
	var token = uni.getStorageSync('token')
	if(!token){
		uni.showToast({
			icon: "none",
			title: "登陆过期，请重新登录",
			duration:'1000',
			complete() {
				setTimeout(function(){
					uni.reLaunch({
						url:'/pages/index/login/login'
					})
				},1000)
			}
		})
	}
	// config.headers['token'] = getToken();
	return new Promise((resolve, reject) => {
		uni.request({
			url: options.url + (options.params ? params(options.params) : ''),
			method: options.method || 'GET',
			data: options.data || '{}',
			header: {
				'Content-Type': 'application/json',
				'timestamp': timestamp,
				'appId': appId,
				'nonce': nonce,
				'signature': lmd5.hex_md5('appId=' + appId + '&nonce=' + nonce + '&timestamp=' +
					timestamp + '&appSecret=originWarehouseSecret').toUpperCase(),
				'token': token || ''
			},
			success: (res) => {
				if (res.statusCode == 200 || res.statusCode == 201) {
					resolve(res.data)
				} else {
					if(res.data.message==='Invalid token'||res.data.code===401){
						uni.showToast({
							icon: "none",
							title: "登陆过期，请重新登录",
							duration:'1000',
							complete() {
								setTimeout(function(){
									uni.reLaunch({
										url:'/pages/index/login/login'
									})
								},1000)
							}
						})
						
					}else{
						uni.showToast({
							icon: "none",
							title: "请求接口失败"
						})
					}
					
				}
			},
			fail: (err) => {
				console.log(12)
				uni.showToast({
					icon: "none",
					title: "请求接口失败"
				})
				reject(err)
			}
		})
	})
}

export default request